<template>
  <div class="app-container">
    <el-card>
      <el-form ref="searchForm" :model="searchForm" size="mini" :inline="true">
        <el-form-item label="企业名称" prop="taxpayerName">
          <el-input style="width: 200px" v-model="searchForm.taxpayerName" placeholder="请输入企业名称" maxlength="200"
            clearable />
        </el-form-item>

        <el-form-item label="税号" prop="creditCode">
          <el-input style="width: 200px" v-model="searchForm.creditCode" maxlength="200" clearable
            placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="查询渠道">
          <el-select style="width: 200px" v-model="searchForm.queryChannel" clearable placeholder="请选择查询渠道" filterable>
            <el-option :value="1" label="助融报告"> </el-option>
            <el-option :value="2" label="顺顺助融"> </el-option>
            <el-option :value="3" label="专家咨询"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalPersonName">
          <el-input style="width: 200px" v-model="searchForm.legalPerson" maxlength="200" placeholder="请输入法人姓名"
            clearable />
        </el-form-item>
        <el-form-item label="所属经理">
          <el-select style="width: 200px" v-model="searchForm.managerId" clearable placeholder="请选择所属经理" filterable>
            <el-option v-for="item in managerList" :key="item.id" :label="item.name + ' ' + '(' + item.phone + ')'"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属省份">
          <el-select filterable clearable style="width: 200px" v-model="searchForm.provinceId" placeholder="请选择所属省份">
            <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="添加时间">
          <el-date-picker clearable style="width: 200px" v-model="searchForm.beginTime" align="right" type="date"
            placeholder="选择开始日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>
        <el-form-item>-</el-form-item>
        <el-form-item>
          <el-date-picker clearable v-model="searchForm.endTime" align="right" type="date" placeholder="选择结束日期"
            :picker-options="pickerOptions" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" @click="resetList">重置</el-button>
          <el-button icon="el-icon-search" type="primary" @click="searchList('searchForm')">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 20px">
        <el-button size="mini" type="primary" icon="el-icon-user" @click="manyTouser()" v-btnpermission="$btnPer.customerEnterpiseBtnrules.assignAccountManager
          ">批量分配客户经理</el-button>
        <el-button v-btnpermission="$btnPer.customerEnterpiseBtnrules.batchDelete" size="mini" icon="el-icon-delete"
          @click="manyDelete()">批量删除</el-button>
      </div>
      <el-table :data="tableData.data" border style="width: 100%" size="mini" @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="编号" width="100" align="center" type="index"></el-table-column>
        <el-table-column align="center" label="会员昵称" prop="memberNickname"></el-table-column>
        <el-table-column align="center" label="会员手机号" prop="memberPhone"></el-table-column>
        <el-table-column align="center" label="公司名称" prop="taxpayerName"></el-table-column>
        <el-table-column align="center" label="税号" prop="creditCode"></el-table-column>
        <el-table-column align="center" label="法人" prop="legalPerson"></el-table-column>
        <el-table-column align="center" label="所属省份" prop="provinceName"></el-table-column>
        <el-table-column align="center" label="客户经理" prop="managerName"></el-table-column>
        <el-table-column sortable align="center" label="添加时间" prop="createTime"></el-table-column>
        <el-table-column align="center" label="查询渠道">
          <template slot-scope="scope">
            <span v-if="scope.row.queryChannel == 1">助融报告</span>
            <span v-if="scope.row.queryChannel == 2">顺顺助融</span>
            <span v-if="scope.row.queryChannel == 3">专家咨询</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button v-btnpermission="$btnPer.customerEnterpiseBtnrules.communicate" size="mini" type="text"
              @click="communicate(scope.row)">沟通</el-button>
            <el-button size="mini" type="text" @click="detail(scope.row)">详情</el-button>
            <el-button v-btnpermission="$btnPer.customerEnterpiseBtnrules.assignAccountManager
              " size="mini" type="text" @click="applyCustomer(scope.row)">分配客户经理</el-button>
            <el-button v-btnpermission="$btnPer.customerEnterpiseBtnrules.deleteCustomer" size="mini" type="text"
              @click="deleteItem(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pageRight" background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]" :current-page="searchForm.pageNum" :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
      </el-pagination>
    </el-card>
    <dialogDiy title="客户信息" :titleCenter="true" ref="dialogDiy" @handleClose="handleClose">
      <div style="overflow-y: auto; height: 70vh" v-if="digflag">
        <!-- <customDetail :id="id" /> -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="客户税务基本信息" name="first">
            <customDetail  v-if="activeName == 'first'" :id="id" />
          </el-tab-pane>
          <el-tab-pane  label="沟通历史记录" name="second">
            <historyList v-if="activeName == 'second'" :id="id" />
          </el-tab-pane>

          <el-tab-pane  label="客户征信报告" name="third">
            <customerReport v-if="activeName == 'third'" :id="enterpriseId"></customerReport>
          </el-tab-pane>
          <el-tab-pane label="客服沟通记录" name="fourth">
            <messageDetail v-if="activeName == 'fourth'" :id="enterpriseId"></messageDetail>
          </el-tab-pane>

        </el-tabs>
      </div>
    </dialogDiy>
    <el-dialog @close="closeMany" title="分配客户经理" :visible.sync="manyDesable" width="600px">
      <div style="padding-bottom: 30px; margin-top: 10px">
        <div style="margin-bottom: 20px">
          <span style="color: #222; font-weight: bold">所属客户经理：</span>
          <span>
            <el-select size="small" multiple style="width: 300px" v-model="manyForm.managerIdList" clearable
              placeholder="请选择所属经理" filterable>
              <el-option v-for="item in managerList" :key="item.id" :label="item.name + ' ' + '(' + item.phone + ')'"
                :value="item.id" />
            </el-select>
          </span>
        </div>
        <el-table :data="manyForm.companyIdList" border size="mini">
          <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
          <el-table-column align="center" label="公司名称" prop="taxpayerName"></el-table-column>
          <el-table-column align="center" label="税号" prop="creditCode"></el-table-column>
          <el-table-column align="center" label="已分配客户经理">
            <template slot-scope="scope">
              <span>{{
                scope.row.bindName ? scope.row.bindName : "未绑定"
                }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center; padding-top: 20px">
          <el-button style="width: 100px" size="mini" type="primary" @click="submitMany">确定</el-button>
          <el-button style="width: 100px" size="mini" @click="closeMany">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import customDetail from "./components/customDetail.vue";
import dialogDiy from "../../../components/dialogDiy/index.vue";
import historyList from "./components/historyList.vue";
import customerReport from "./components/customerReport.vue";
import messageDetail from "./components/messageDetail.vue";
import { getProvinceList } from "@/api/tax";
import { getUserList } from "@/api/dept";
import { timeFun } from "../../../utils/date";
import { datePickerOptions } from "../options";
import {
  getCompanyCustomerList,
  assignCustomerManager,
  checkCustomerManager,
  deleteCompanyCustomer,
  deleteMatch,
  getCustomerManagerList,
  getsalesmanList
} from "../../../api/customer";

export default {
  components: {
    dialogDiy,
    historyList,
    customDetail,
    customerReport,
    messageDetail
  },
  name: "index",
  data() {
    return {
      searchForm: {
        taxpayerName: "",
        creditCode: "",
        legalPersonName: "",
        managerId: "",
        provinceId: "",
        beginTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10,
        type: 2,
        queryChannel: ''
      },
      tableData: {
        data: [],
        total: 0
      },
      pickerOptions: datePickerOptions,
      managerList: [],
      salesmanList: [],
      provinceList: [],
      activeName: "first",
      id: "",
      enterpriseId: '',
      manyDesable: false,
      manyForm: {
        companyIdList: [],
        managerIdList: []
      },
      selectList: [],
      digflag: false
    };
  },
  created() {
    const p1 = getProvinceList();
    const p2 = getCustomerManagerList();
    Promise.all([p1, p2]).then(res => {
      if (res[1].data) {
        this.managerList = res[1].data.map(v => {
          return {
            name: v.nickName,
            id: v.adminId,
            phone: v.phoneNumber
          };
        });
      }

      this.provinceList = res[0].data;
      this.getlist();
    });
  },
  mounted() { },
  methods: {
    handleClose() {
      this.digflag = false;
    },
    manyDelete() {
      if (this.selectList.length === 0) {
        this.$message({
          message: "请选择客户",
          type: "warning"
        });
      } else {
        this.$confirm("是否删除该客户？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          deleteCompanyCustomer(this.selectList.map(v => v.id)).then(res => {
            console.log(res);
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getlist();
          });
        });
      }
    },
    deleteItem(v) {
      this.$confirm("是否删除该客户？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        deleteMatch(v.id).then(res => {
          console.log(res);
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.getlist();
        });
      });
    },
    closeMany() {
      this.manyForm = {
        companyIdList: [],
        managerIdList: []
      };
      this.manyDesable = false;
    },
    submitMany() {
      if (this.manyForm.managerIdList.length === 0) {
        this.$message({
          message: "请选择客户经理",
          type: "warning"
        });
      } else {
        let params = {
          companyIdList: this.manyForm.companyIdList.map(v => v.id),
          managerIdList: this.manyForm.managerIdList
        };
        checkCustomerManager(params).then(res => {
          if (res.data) {
            let str = "";
            let stv = "";
            const arr = res.data.filter(v => v.contactedStatus);
            console.log("arr", arr);
            if (arr.length > 0) {
              str = arr
                .map(v => v.companyName + "-" + v.managerName + "有沟通记录")
                .join(",");
              this.bindconfirm(arr, str, params);
            } else {
              let flag = res.data.every(v => {
                return !v.bindStatus && !v.contactedStatus;
              });
              console.log(flag, "flag");
              if (flag) {
                this.bindCustomer(params);
                this.getlist();
              } else {
                str = res.data
                  .map(
                    v =>
                      "(" +
                      v.companyName +
                      ")" +
                      "->" +
                      `${v.bindStatus ? "已经分配给" : "还没分配给"}` +
                      v.managerName
                  )
                  .join(" , ");
                this.bindconfirm(arr, str, params);
              }
            }
          }
        });
      }
    },

    //绑定前确认
    bindconfirm(arr, str, params) {
      let stV = "";
      stV =
        arr.length > 0
          ? `${str} 是否要重新分配？`
          : `您选择的公司名称 ${str} 了, 是否要重新分配`;
      if (str) {
        this.$confirm(`${stV}`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          await this.bindCustomer(params);
        });
      } else {
        this.bindCustomer(params);
      }
    },

    bindCustomer(data) {
      assignCustomerManager(data).then(res => {
        if (res.data) {
          this.$message({
            message: "分配成功",
            type: "success"
          });
          this.closeMany();
          this.manyDesable = false;
          this.getlist();
        }
      });
    },

    manyTouser() {
      if (this.selectList.length === 0) {
        this.$message({
          message: "请选择客户",
          type: "warning"
        });
      } else {
        this.manyForm.companyIdList = this.selectList.map(v => {
          return {
            id: v.id,
            taxpayerName: v.taxpayerName,
            creditCode: v.creditCode,
            bindName: v.managerName
          };
        });
        console.log(this.manyForm.companyIdList);
        this.manyDesable = true;
      }
    },
    handleSelectionChange(v) {
      this.selectList = v;
    },
    applyCustomer(row) {
      let obj = {
        id: row.id,
        taxpayerName: row.taxpayerName,
        creditCode: row.creditCode,
        bindName: row.managerName
      };
      this.manyForm.companyIdList = [obj];
      this.manyDesable = true;
    },
    communicate(v) {
      console.log(v);
      this.$router.push({
        path: "/customer/communicate",
        query: {
          id: v.id
        }
      });
    },
    detail(v) {
      this.id = v.id;
      this.enterpriseId = v.enterpriseId
      this.digflag = true;
      this.$refs.dialogDiy.openlog();
    },
    searchList() {
      this.searchForm.pageNum = 1;
      this.getlist();
    },
    resetList() {
      this.searchForm = {
        taxpayerName: "",
        creditCode: "",
        legalPersonName: "",
        managerId: "",
        provinceId: "",
        beginTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10,
        type: 2
      };
      this.getlist();
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val; // 更新搜索表单的每页记录数
      this.getlist(); // 重新获取列表数据
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.getlist();
    },
    getlist() {
      if (
        (this.searchForm.beginTime && !this.searchForm.endTime) ||
        (!this.searchForm.beginTime && this.searchForm.endTime)
      ) {
        return this.$message.warning("请填写开始日期或者结束日期哦");
      } else {
        console.log("111");
      }

      if (this.searchForm.beginTime && this.searchForm.endTime) {
        if (!timeFun(this.searchForm.beginTime, this.searchForm.endTime)) {
          return this.$message.warning("结束时间必须大于开始时间");
        } else {
          console.log("222");
        }
      }
      this.getCompanyCustomerList();
    },
    getCompanyCustomerList() {
      this.listLoading = true;
      getCompanyCustomerList(this.searchForm)
        .then(res => {
          this.tableData.data = res.data.list;
          this.tableData.total = res.data.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  height: calc(100vh - 50px);
  background-color: #f5f5f5;
  position: relative;
}

/deep/ .el-dialog__body {
  padding: 0 20px;
}
</style>
